﻿using System;
using System.Reflection;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel;

namespace PmSoft.Utilities
{
    public static class ObjectUtility
    {
        /// <summary>
        /// 对比两个相同类型对象,返回差异的旧值集合
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="oldObj"></param>
        /// <param name="newObj"></param>
        /// <returns></returns>
        public static Dictionary<string, object?> Compare<T>(T oldObj, T newObj)
        {
            var differences = new Dictionary<string, object?>();

            PropertyInfo[] mPi = typeof(T).GetProperties();
            PropertyInfo[] mPi1 = typeof(T).GetProperties();
            for (int i = 0; i < mPi.Length; i++)
            {
                PropertyInfo pi = mPi[i];
                var displayNameAttr = pi.GetCustomAttribute<DisplayNameAttribute>();
                if (displayNameAttr == null)
                    continue;
                for (int j = 0; j < mPi1.Length; j++)
                {
                    PropertyInfo pi1 = mPi1[j];
                    if (pi.Name == pi1.Name)
                    {
                        object? oldValue = pi.GetValue(oldObj, null);
                        object? newValue = pi1.GetValue(newObj, null);
                        if (oldValue != newValue)
                            differences.Add(displayNameAttr.DisplayName, oldValue);
                    }
                }
            }
            return differences;
        }
    }
}
